<template>
  <view class="login-container">
    <uni-icons
      class="login-avatar"
      type="contact-filled"
      size="100"
      color="#efefef"
    ></uni-icons>
    <button class="login-btn" type="primary" @click="getUserInfo">
      一键登录
    </button>
    <view class="login-text">登录享受更多权益</view>
  </view>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  name: 'my-login',
  data() {
    return {}
  },
  methods: {
    ...mapMutations('user', {
      updateUsaerInfo: 'updateUsaerInfo',
      updateToken: 'updateToken'
    }),
    async getUserInfo() {
      const [err, data] = await uni.getUserProfile({
        desc: '用户信息授权'
      })
      if (err && err.errMsg === 'getUserProfile:fail auth deny') {
        uni.showToast({
          title: `您取消了授权`,
          icon: 'none'
        })
        return
      }
      this.updateUsaerInfo(data.userInfo)
      this.getToken(data)
    },
    async getToken(info) {
      const [err, res] = await uni.login().catch(error => error)
      if (err || res.errMsg !== 'login:ok') {
        uni.showToast({
          title: `登录失败`,
          icon: 'none'
        })
        return
      }
      const query = {
        code: res.code,
        encryptedData: info.encryptedData,
        iv: info.iv,
        rawData: info.rawData,
        signature: info.signature
      }
      //获取登陆token
      const { data } = await uni.$http.post(
        '/api/public/v1/users/wxlogin',
        query
      )
      // if (data.meta.status !== 200) return uni.$errShowMes()//必定失败,接口问题
      //在这里设置给个概率,如果出的随机数大于0.8就登陆失败，Math.random()生成1以内随机小数
      if (Math.random() > 0.8) {
        return uni.showToast({
          title: `获取token失效，登录失败`,
          icon: 'none'
        })
      }
      //存储token
      const resToken =
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
      this.updateToken(resToken)
    }
  }
}
</script>

<style lang="scss">
.login-container {
  height: 750rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  .login-avatar {
  }
  .login-btn {
    min-width: 70%;
    margin: 10px 0;
    border-radius: 50px;
  }
  .login-text {
    font-size: 12px;
    color: #9c9c9c;
  }
}
</style>
